package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.annotation.RequestInfo;
import org.example.config.ApiConfig;
import org.example.entity.BmsControl;
import org.example.entity.BusinessStatus;
import org.example.service.impl.BaseInfoServiceImpl;
import org.example.service.impl.DeviceService;
import org.example.util.DeviceUtil;
import org.example.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import static org.example.enums.ResultCode.*;

@RestController
@RequestMapping("/openapi/v1.0/gateway")
@CrossOrigin
@Slf4j
public class BaseInfoController {
    @Autowired
    private BaseInfoServiceImpl baseInfoServiceImpl;
    @Autowired
    private DeviceService deviceService;


    /**
     * 1.1查询电池包基本信息
     * @param imei
     *
     * @return 查询结果
     */

    @GetMapping("/detail")
    @ResponseBody  //返回json
//    public Result getBatteryBaseInfo(@RequestParam("packNo") String packNo,@RequestParam(value = "imei",required = false) String imei,
//                                     @RequestHeader(value = "Authorization",required = false)String bearToken)
    public Result getBatteryBaseInfo(@RequestParam(value = "imei") String imei,
                                  @RequestHeader(value = "Authorization",required = false)String bearToken){
        log.info("getBaseInfo... imei="+imei);
        if(bearToken==null){
            return new Result(TOKEN_NOT_EXIST.code,false,null,"accessToken not exits");
        }
        String token=bearToken.substring(7,bearToken.length());
        return baseInfoServiceImpl.getBaseInfo(imei,token);
    }

    /**
     * 1.2查询电池包列表
     * @param imei
     * @param onOffStatus
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/list")
    @ResponseBody
    public Result getBatteryList(@RequestParam(value = "imei",required = false) String imei,//@RequestParam(value = "packNo",required = false) String packNo,//改之前
                                 @RequestParam(value = "onOffStatus",required = false) Integer onOffStatus,
                                 @RequestParam(value = "current",defaultValue = "1")Integer current,
                                 @RequestParam(value = "size",defaultValue = "20")Integer size,
                                 @RequestHeader(value = "Authorization",required = false)String bearToken){
        log.info("getBatteryList... imei="+imei+" onOffStatus="+onOffStatus+" current="+current+" size=",size);
        if(bearToken==null){
            return new Result(TOKEN_NOT_EXIST.code,false,null,"accessToken not exits");
        }
        String token=bearToken.substring(7,bearToken.length());
//        //根据imei获取packNo
//        String uuid= IMEIUtil.getLatestDevice(imei,token);
//        if(uuid==null){
//            return new Result(FAIL.code,false,null,"Cannot get DeviceID from imei"+imei);
//        }
//        String packNo=DeviceUtil.getKey(uuid);
//        log.info("imei:"+imei+" uuid:"+uuid+" packNo:"+packNo);
        // 去掉了通过在线率筛选的功能，毫无意义
//        return baseInfoServiceImpl.getBatteryList(imei,onOffStatus,current,size,token);
        return baseInfoServiceImpl.getBatteryList(imei,null,current,size,token);
    }

    /**
     * 1.3电池包实时信息
     * @return
     */
    @GetMapping("/getStatusInfo")
    @ResponseBody  //返回json
    //改之前(@RequestParam("packNo")String packNo,@RequestHeader(value = "Authorization",required = false)String bearToken)
    public Result getStatusInfo(@RequestParam("imei")String imei,@RequestHeader(value = "Authorization",required = false)String bearToken){
        log.info("getStatusInfo... imei="+imei);
        if(bearToken==null){
            return new Result(TOKEN_NOT_EXIST.code,false,null,"accessToken not exits");
        }
        String token=bearToken.substring(7,bearToken.length());
        return baseInfoServiceImpl.getStatusInfo(imei,token);
    }


    /**
     * 1.4电池包下所有单体电芯电压
     * @param imei
     * @return
     */
    @GetMapping("/getCellVols")
    @ResponseBody  //返回json
    //之前(@RequestParam("packNo")String packNo,@RequestHeader(value = "Authorization",required = false)String bearToken)
    public Result getCellVols(@RequestParam("imei")String imei,@RequestHeader(value = "Authorization",required = false)String bearToken){
        log.info("getCellVols... imei="+imei);
        if(bearToken==null){
            return new Result(TOKEN_NOT_EXIST.code,false,null,"accessToken not exits");
        }
        String token=bearToken.substring(7,bearToken.length());
        return baseInfoServiceImpl.getCellVols(imei,token);
    }



    /**
     * 1.5 GPS实时定位信息
     * @param imei
     * @return
     */
    @GetMapping("/getGpsInfo")
    @ResponseBody  //返回json
    //(@RequestParam("packNo")String packNo,
    // @RequestHeader(value = "Authorization",required = false)String bearToken)
    public Result getGpsInfo(@RequestParam("imei")String imei,
                             @RequestHeader(value = "Authorization",required = false)String bearToken){
        log.info("getGpsInfo... imei="+imei);
        if(bearToken==null){
            return new Result(TOKEN_NOT_EXIST.code,false,null,"accessToken not exits");
        }
        String token=bearToken.substring(7,bearToken.length());
        return baseInfoServiceImpl.getGpsInfo(imei,token);
    }

    /**
     * 1.6 GPS历史轨迹信息
     * @param imei
     * @return
     */
    @GetMapping("/getGpsHisInfo")
    @ResponseBody  //返回json
    //(@RequestParam("packNo")String packNo,@RequestParam("startTime")String startTime,@RequestParam("endTime")String endTime,
    // @RequestHeader(value = "Authorization",required = false)String bearToken)
    public Result getGpsHisInfo(@RequestParam("imei")String imei,@RequestParam("startTime")String startTime,@RequestParam("endTime")String endTime,
                                @RequestHeader(value = "Authorization",required = false)String bearToken){
        log.info("getGpsHisInfo... imei="+" startTime="+startTime+" endTime="+endTime);
        //日期转时间戳
        long startTs=0;
        long endTs=0;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date startDate = simpleDateFormat.parse(startTime);
            Date endDate=simpleDateFormat.parse(endTime);
            startTs=startDate.getTime();
            endTs=endDate.getTime();
        } catch (ParseException e) {
            return new Result(FAIL.code,false,null,"Date format should be like yyyy-MM-dd HH:mm:ss");
        }
        if(bearToken==null){
            return new Result(TOKEN_NOT_EXIST.code,false,null,"accessToken not exits");
        }
        String token=bearToken.substring(7,bearToken.length());
        if(startTs>=endTs){
            return new Result(FAIL.code,false,null,"StartTime should be earlier than endTime");
        }
        return baseInfoServiceImpl.getGpsHisInfo(imei,startTs, endTs,token);
    }

    /**
     * 1.7 查询实时告警
     * @param imei
     * @return
     */
    @GetMapping("/getAlarmInfo")
    @ResponseBody  //返回json
    //(@RequestParam("packNo")String packNo,
    //                                @RequestHeader(value = "Authorization",required = false)String bearToken)
    public Result getAlarmInfo(@RequestParam("imei")String imei,
                                @RequestHeader(value = "Authorization",required = false)String bearToken){
        log.info("getAlarmInfo... imei="+imei);
        if(bearToken==null){
            return new Result(TOKEN_NOT_EXIST.code,false,null,"accessToken not exits");
        }
        String token=bearToken.substring(7,bearToken.length());
        return baseInfoServiceImpl.getAlarmInfo(imei,token);
    }

    /**
     * 1.8 查询电池包开关状态
     * @param imei
     * @return
     */
    @GetMapping("/getBmsSwitch")
    @ResponseBody  //返回json
    //(@RequestParam("packNo")String packNo,
    //                               @RequestHeader(value = "Authorization",required = false)String bearToken)
    public Result getBmsSwitch(@RequestParam("imei")String imei,
                               @RequestHeader(value = "Authorization",required = false)String bearToken){
        log.info("getBmsSwitchInfo... imei="+imei);
        if(bearToken==null){
            return new Result(TOKEN_NOT_EXIST.code,false,null,"accessToken not exits");
        }
        String token=bearToken.substring(7,bearToken.length());
        return baseInfoServiceImpl.getBmsSwitch(imei,token);
    }

    /**
     * 控制指令接口：电池包开启关闭
     * @return
     */
    @PostMapping("/bmsSwitch")
    @ResponseBody
    @RequestInfo  // 切点注解，添加此注解的方法调用时会打印参数和调用者IP
    @Deprecated
    public Result bmsSwitch(@RequestBody BmsControl bmsControl, @RequestHeader(value = "Authorization",required = false)String bearToken){
//        System.out.println(TokenUtil.token);
        log.info("setBmsSwitchInfo... bmsControl="+bmsControl);
        if(bmsControl.getControl()==null){
            return new Result(FAIL.code,false,null,"Please input control");
        }
        if(bmsControl.getControl()!=0&&bmsControl.getControl()!=1){
            return new Result(FAIL.code,false,null,"Please input correct control");
        }
        if(bmsControl.getImei()==null){
            return new Result(FAIL.code,false,null,"Please input imei");
        }
        if(bearToken==null){
            return new Result(TOKEN_NOT_EXIST.code,false,null,"accessToken not exits");
        }
        String token=bearToken.substring(7,bearToken.length());
        //根据imei获取packNo
        String imei=bmsControl.getImei();

//        return baseInfoServiceImpl.setBmsSwitch(imei,bmsControl.getControl(),token);
        return baseInfoServiceImpl.setbmsControl(imei,bmsControl.getControl());
    }



    /**
     * 手动刷新设备列表
     */
    @GetMapping("/refreshDevice")
    public Result refreshDevice(){
        boolean flag=deviceService.refreshDevice("tenant@thingsboard.org","tenant");
        if(!flag){
            return new Result(FAIL.code,false,"false","refresh failed");
        }
        return new Result(SUCCESS.code,true,"true","refresh success");
    }

    /**
     * 由imei获取uuid
     */
    @GetMapping("/getUUID")
    public String getUUID(@RequestParam("imei")String imei){
        return deviceService.getUUIDByImei(imei);
    }


    /**
     * @author plyn
     * 3.3 日里程和电量统计
     * 暂时未完成，仅返回currentDay，chargeSum和disChargeSum
     */
    @GetMapping("/cardistanceday/page")
    @ResponseBody
    public Result calCarDistanceDay(
                                    @RequestParam(value = "imei") String imei,
                                    @RequestParam(value = "startDate") String startDate,
                                    @RequestParam(value = "endDate") String endDate,
                                    @RequestHeader(value = "Authorization", required = false) String bearToken) throws ParseException {
        if (bearToken == null) {
            return new Result(TOKEN_NOT_EXIST.code, false, null, "accessToken not exits");
        }
        String token = bearToken.substring(7, bearToken.length());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startDateForm = sdf.parse(startDate);
        Date endDateForm = sdf.parse(endDate);

        // 暂时
        return baseInfoServiceImpl.calCarDistanceDay(imei, token, startDateForm, endDateForm);
    }

    /**
     * @author plyn
     * 3.10 查询当前（最后一次）充放电量
     */
    @GetMapping("/getElectricLatest")
    @ResponseBody
    public Result getElectricLatest(
                              @RequestParam(value = "imei") String imei,
                              @RequestParam(value = "chargeStatus", required = false) Integer chargeStatus,
                              @RequestHeader(value = "Authorization") String bearToken) throws ParseException {
        if (bearToken == null) {
            return new Result(TOKEN_NOT_EXIST.code, false, null, "accessToken not exits");
        }
        String token = bearToken.substring(7, bearToken.length());

        return baseInfoServiceImpl.getElectricLatest(imei, token, chargeStatus);
    }

    /**
     * @author plyn
     * 3.11 历史充放电电量查询
     */
    @GetMapping("/getElectric/page")
    @ResponseBody
    public Result getElectric(
                              @RequestParam(value = "imei") String imei,
                              @RequestParam(value = "startTime") String startTime,
                              @RequestParam(value = "endTime") String endTime,
                              @RequestHeader(value = "Authorization", required = false) String bearToken) throws ParseException {
        if (bearToken == null) {
            return new Result(TOKEN_NOT_EXIST.code, false, null, "accessToken not exits");
        }
        String token = bearToken.substring(7, bearToken.length());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startTimeForm = sdf.parse(startTime);
        Date endTimeForm = sdf.parse(endTime);

        return baseInfoServiceImpl.getElectric(imei, token, startTimeForm, endTimeForm);
    }

    /**
     * @author plyn
     * 3.12 历史充放电电量汇总查询
     */
    @GetMapping("/getElectricSum")
    @ResponseBody
    public Result getElectricSum(
                              @RequestParam(value = "imei") String imei,
                              @RequestParam(value = "startTime") String startTime,
                              @RequestParam(value = "endTime") String endTime,
                              @RequestParam(value = "chargeStatus") Integer chargeStatus,
                              @RequestHeader(value = "Authorization", required = false) String bearToken) throws ParseException {
        if (bearToken == null) {
            return new Result(TOKEN_NOT_EXIST.code, false, null, "accessToken not exits");
        }
        String token = bearToken.substring(7, bearToken.length());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startTimeForm = sdf.parse(startTime);
        Date endTimeForm = sdf.parse(endTime);
        return baseInfoServiceImpl.getElectricSum(imei, token, startTimeForm, endTimeForm, chargeStatus);
    }

    /**
     * extra 1 电池使用统计报表
     */
    @GetMapping("/getUsageInfo")
    @ResponseBody
    public Result getUsageInfo(@RequestParam(value = "imei") String imei,
                               @RequestParam(value = "date") String date,
                               @RequestHeader(value = "Authorization", required = false) String bearToken){
        if (bearToken == null) {
            return new Result(TOKEN_NOT_EXIST.code, false, null, "accessToken not exits");
        }
        String token = bearToken.substring(7, bearToken.length());
        return baseInfoServiceImpl.getUsageInfo(imei,date,token);
    }

    /**
     * extra 2 充电记录接口
     */
    @GetMapping("/getChargeRecords")
    @ResponseBody
    public Result getChargeRecords(@RequestParam(value = "imei") String imei,
                                   @RequestParam(value = "startTime") String startTime,
                                   @RequestParam(value = "endTime") String endTime,
                               @RequestHeader(value = "Authorization", required = false) String bearToken) throws ParseException {
        if (bearToken == null) {
            return new Result(TOKEN_NOT_EXIST.code, false, null, "accessToken not exits");
        }
        String token = bearToken.substring(7, bearToken.length());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startTimeForm = sdf.parse(startTime);
        Date endTimeForm = sdf.parse(endTime);
        return baseInfoServiceImpl.getChargeRecords(imei,startTimeForm,endTimeForm,token);
    }

    /**
     * extra 3 电池历史信息接口
     */
    @GetMapping("/getBatteryHisInfo")
    @ResponseBody
    public Result getBatteryHisInfo(@RequestParam(value = "imei") String imei,
                                   @RequestParam(value = "startTime") String startTime,
                                   @RequestParam(value = "endTime") String endTime,
                                   @RequestHeader(value = "Authorization", required = false) String bearToken) throws ParseException {
        if (bearToken == null) {
            return new Result(TOKEN_NOT_EXIST.code, false, null, "accessToken not exits");
        }
        String token = bearToken.substring(7, bearToken.length());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startTimeForm = sdf.parse(startTime);
        Date endTimeForm = sdf.parse(endTime);
        return baseInfoServiceImpl.getBatteryHisInfo(imei,startTimeForm,endTimeForm,token);
    }
    /**
     * extra 4 业务状态接口
     */
    @PostMapping("/businessStatus")
    @ResponseBody
    public Result setBusinessStatus(@RequestBody BusinessStatus businessStatus, @RequestHeader(value = "Authorization",required = false)String bearToken){
//        System.out.println(TokenUtil.token);
        Integer status=businessStatus.getBusinessStatus();
        if(status!=0&&status!=1&&status!=2){
            return new Result(FAIL.code,false,null,"Please input correct business status!");
        }
        String imei=businessStatus.getImei();
        if(imei==null){
            return new Result(FAIL.code,false,null,"Please input imei");
        }
        if(bearToken==null){
            return new Result(TOKEN_NOT_EXIST.code,false,null,"accessToken not exits");
        }
        String token=bearToken.substring(7,bearToken.length());
        return baseInfoServiceImpl.setBusinessStatus(imei,status,token);
    }



}
